package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.WatchService;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 通用方法简化代码
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> dateList(LocalDate begin, LocalDate end) {

        //存放begin到end的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        //begin == end 就退出
        while (!begin.equals(end)){
            //begin.plusDays日期的加，减
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        return dateList;
    }

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        /*//存放begin到end的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        //begin == end 就退出
        while (!begin.equals(end)){
            //begin.plusDays日期的加，减
            begin = begin.plusDays(1);
            dateList.add(begin);
        }*/

        List<LocalDate> dateList = dateList(begin, end);

        //字符拼接StringUtils.join
        String join = StringUtils.join(dateList, ",");

        List<Double> doubles = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //查询localDate日期当天对应的营业金额，状态为已完成
            //LocalDateTime.of(localDate, LocalTime.MIN)获取当天最开始的时间
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            //LocalDateTime.of(localDate, LocalTime.MIN)获取当天距离第二天最近的时间
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            Double sunStatistics = orderMapper.sunBy(map);

            sunStatistics = sunStatistics == null? 0.0 : sunStatistics;

            doubles.add(sunStatistics);
        }

        return TurnoverReportVO
                .builder()
                .dateList(join)
                .turnoverList(StringUtils.join(doubles, ","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
//        List<LocalDate> dateTime = new ArrayList<>();
//        dateTime.add(begin);
//
//        while (!begin.equals(end)){
//            begin = begin.plusDays(1);
//            dateTime.add(begin);
//        }

        List<LocalDate> dateTime = dateList(begin, end);

        String join = StringUtils.join(dateTime, ",");

        List<Integer> total = new ArrayList<>();
        List<Integer> newUser = new ArrayList<>();
        for (LocalDate time : dateTime) {
            //一天最开始时间
            LocalDateTime beginTime = LocalDateTime.of(time, LocalTime.MIN);
            //一天最后时间
            LocalDateTime endTime = LocalDateTime.of(time, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("end", endTime);
            Integer aDouble = userMapper.userStatistics(map);
            aDouble = aDouble == null? 0 : aDouble;
            total.add(aDouble);

            map.put("begin", beginTime);
            aDouble = userMapper.userStatistics(map);
            aDouble = aDouble == null? 0 : aDouble;
            newUser.add(aDouble);
        }


        return UserReportVO.builder()
                .dateList(join)
                .totalUserList(StringUtils.join(total, ","))
                .newUserList(StringUtils.join(newUser, ","))
                .build();
    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderFulfillmentRate(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = dateList(begin, end);

        List<Integer> orderCountList = new ArrayList<>(); //订单总数集合
        List<Integer> validOrderCountList = new ArrayList<>(); //有效订单数集合
        for (LocalDate localDate : dateList) {
            //一天最开始时间
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            //一天最后时间
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap<>();

            map.put("begin", beginTime);
            map.put("end", endTime);
            //查出订单每天总数
            Integer orderCountInt = orderMapper.orderStatistics(map);
            orderCountInt = orderCountInt == null ? 0 : orderCountInt;
            orderCountList.add(orderCountInt);
            //查出订单每天有效总数
            map.put("status", Orders.COMPLETED);
            Integer validOrderCountInt = orderMapper.orderStatistics(map);
            validOrderCountInt = validOrderCountInt == null ? 0 : validOrderCountInt;
            validOrderCountList.add(validOrderCountInt);
        }

        // 使用stream流运算
        //将orderCountList集合遍历一遍然后求和的操作
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get(); //订单总数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get(); //有效订单数

        //订单完成率
        Double orderCompletionRate = 0.0;
        //判断
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询销量排名top10接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO sales(LocalDate begin, LocalDate end) {

        //一天最开始时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        //一天最后时间
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> getSales = orderMapper.getSales(beginTime, endTime);

        List<String> nameList = getSales.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = getSales.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出Excel报表
     */
    @Override
    public void export(HttpServletResponse response) {

        //1. 查询数据路，获取营业数据--查询最近30天运营数据
        // LocalDate.now().minusDays(30)运算30天前的日期
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        //运算昨天前的日期
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);
        //2. 通过POI将数据写入到Excel文件中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(is);

            //获取表格文件的Sheet页
            XSSFSheet sheet1 = excel.getSheet("Sheet1");

            //填充数据--
            sheet1.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获取第四行
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            //获得第5行
            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的数据
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet1.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());
            }


            //3. 通过输出流将Excel文件下载到客户端
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
